package de.herberlin.colormatcher;

import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ResourceBundle;

import javax.swing.*;

/**
 * Main and UI class for colormatcher.
 *
 * @author hans joachim herbertz
 * created 11.07.2003
 */
public class Colormatcher extends JPanel implements ClipboardOwner {
    
    public static final String VERSION = "Colormatcher v. 0.3";
    public static final int NO_COLORS = 6;
    private Spot[] spots = new Spot[NO_COLORS];
    private JTextField rgbField = new JTextField(6);
    private JPopupMenu inputPop = null;
    
    /**
     * Constructor
     */
    public Colormatcher() {
        init();
        
    }
    /**
     * Makes ui.
     */
    private void init() {
        setLayout(new BorderLayout());
        
        // color display area
        JPanel p = new JPanel(new GridLayout(1, 6));
        add(p, BorderLayout.CENTER);
        for (int i = 0; i < NO_COLORS; i++) {
            spots[i] = new Spot(new RGB());
            p.add(spots[i]);
        }
        
        // control panel
        JPanel p2 = new JPanel(new FlowLayout());
        inputPop = new JPopupMenu();
        ActionMap map = rgbField.getActionMap();
        String[] actionNames =
                new String[] { "copy-to-clipboard", "paste-from-clipboard" };
                String[] displayNames = new String[] { getBundle().getString("Copy") , getBundle().getString("Paste") };
                for (int i = 0; i < actionNames.length; i++) {
                    Action action = map.get(actionNames[i]);
                    action.putValue(Action.NAME, displayNames[i]);
                    inputPop.add(action);
                }
                rgbField.addMouseListener(new MouseAdapter() {
                    public void mousePressed(MouseEvent e) {
                        shopPop(e);
                    }
                    public void mouseReleased(MouseEvent e) {
                        shopPop(e);
                    }
                    private void shopPop(MouseEvent e) {
                        if (e.isPopupTrigger()) {
                            inputPop.show(
                                    (Component) e.getSource(),
                                    e.getX(),
                                    e.getY());
                        }
                    }
                });
                p2.add(rgbField);
                JButton rgbInput = new JButton(getBundle().getString("Set"));
                rgbInput.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        try {
                            RGB rgb = new RGB(rgbField.getText());
                            setMatchingColors(rgb);
                        } catch (Throwable t) {
                            showError(t);
                        }
                    }
                });
                p2.add(rgbInput);
                
                JButton chooserButton = new JButton(getBundle().getString("Choose"));
                chooserButton.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        Color color =
                                JColorChooser.showDialog(
                                null,
                                getBundle().getString("Choose_Color"),
                                spots[0].getColor());
                        if (color != null) {
                            try {
                                setMatchingColors(new RGB(color));
                            } catch (Throwable t) {
                                showError(t);
                            }
                        }
                    }
                });
                p2.add(chooserButton);
                
                JButton newButton = new JButton(getBundle().getString("New"));
                newButton.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        createFrame();
                    }
                });
                p2.add(newButton);
                
                JButton clipboard = new JButton(getBundle().getString("Clipboard"));
                clipboard.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        copyImageToClipboard();
                    }
                });
                p2.add(clipboard);
                
                JButton aboutButton = new JButton(getBundle().getString("About"));
                aboutButton.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        showHelp();
                    }
                    
                });
                p2.add(aboutButton);
                
                add(p2, BorderLayout.SOUTH);
    }
    
    private void copyImageToClipboard() {
        int width=360;
        int height=60;
        int step=width/NO_COLORS;
        
        BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        Graphics g=image.getGraphics();
        for (int i=0;i<NO_COLORS;i++){
            g.setColor(spots[i].getColor());
            g.fillRect(i*step,0,step,height);
            g.setColor(spots[i].getTextColor());
            g.drawString(spots[i].getRGBString(),(i*step)+5,15);
        }
        Clipboard clipboard=Toolkit.getDefaultToolkit().getSystemClipboard();
        clipboard.setContents(new ImageTransferable(image),this);
    }
    
    class ImageTransferable implements Transferable {
        private Image image=null;
        public ImageTransferable(Image image){
            this.image=image;
        }
        /**
         * @see java.awt.datatransfer.Transferable#getTransferDataFlavors()
         */
        public DataFlavor[] getTransferDataFlavors() {
            return new DataFlavor[]{DataFlavor.imageFlavor};
        }
        
        /**
         * @see java.awt.datatransfer.Transferable#isDataFlavorSupported(java.awt.datatransfer.DataFlavor)
         */
        public boolean isDataFlavorSupported(DataFlavor flavor) {
            if (DataFlavor.imageFlavor.equals(flavor)) {
                return true;
            } else {
                return false;
            }
        }
        
        /**
         * @see java.awt.datatransfer.Transferable#getTransferData(java.awt.datatransfer.DataFlavor)
         */
        public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
            if (DataFlavor.imageFlavor.equals(flavor)) {
                return image;
            } else {
                return null;
            }
        }
        
    }
    private void showHelp() {
        try {
            JDialog dialog = new JDialog((JFrame) null, VERSION);
            dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
            dialog.getContentPane().setLayout(new BorderLayout());
            JEditorPane edit =
                    new JEditorPane(getClass().getResource("/colormatcher.html"));
            edit.setEditable(false);
            dialog.getContentPane().add(
                    new JScrollPane(edit),
                    BorderLayout.CENTER);
            dialog.setSize(320, 240);
            dialog.show();
        } catch (Throwable e) {
            showError(e);
        }
    }
    
    /**
     * Calculates six matching colors and sets
     * the pots to the new colors.
     * @param initial
     */
    private void setMatchingColors(RGB initial) {
        RGB[] colors = Matcher.sixColors(initial);
        for (int i = 0; i < Math.min(colors.length, spots.length); i++) {
            spots[i].setRGB(colors[i]);
        }
        rgbField.setText(colors[0].toString());
    }
    
    /**
     * Displays java exception in a message dialog.
     * @param t
     */
    private void showError(Throwable t) {
        t.printStackTrace();
        JOptionPane.showMessageDialog(
                this,
                t.getLocalizedMessage(),
                t.getClass().getName(),
                JOptionPane.ERROR_MESSAGE);
    }
    
    /**
     * Creates a new Colormatcher frame.
     *
     */
    private static void createFrame() {
        JFrame frame = new JFrame(VERSION);
        try {
            frame.setIconImage(
                    new ImageIcon(
                    new Object().getClass().getResource("/colormatcher32.jpg"))
                    .getImage());
        } catch (Throwable e) {
            e.printStackTrace();
        }
        frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        frame.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e) {
                e.getWindow().dispose();
                openWindowCounter--;
                if (openWindowCounter<=0) {
                    System.exit(0);
                }
            }
            
        });
        frame.getContentPane().add(new Colormatcher());
        frame.pack();
        frame.show();
        openWindowCounter++;
        
    }
    private static int openWindowCounter=0;
    
    /**
     * Main
     * @param args
     */
    public static void main(String[] args) {
        try {
            // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Throwable e1) {
            e1.printStackTrace();
        }
        createFrame();
    }
    /**
     * @see java.awt.datatransfer.ClipboardOwner#lostOwnership(java.awt.datatransfer.Clipboard, java.awt.datatransfer.Transferable)
     */
    public void lostOwnership(Clipboard clipboard, Transferable contents)  {
        
    }
    /**
     * Get the resourced bunble for this application
     */
    public static ResourceBundle getBundle() {
        return ResourceBundle.getBundle("colormatcher");
    }
}
